package com.zzb.framework.common;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 基本的增删改查mapper
 * Created by 瑱彬 on 2016/9/18.
 */
@Component
public abstract class BaseDAO<T extends BaseEntity> {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public abstract <MAPPER extends BaseMapper<T>> MAPPER getMapper();

    /**
     * 注入JpaRepository
     */

    protected JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public T selectById(Serializable id) {
        return getMapper().selectById(id);
    }

    public void trashList(T t, String updater) {
        t.setUpdater(updater);
        t.setActivate(-1);
        t.setUpdateTime(new Date());
        int i = getMapper().updateById(t);
        if (i == 0) throw new DAOException("删除失败！没找到指定记录！");
    }

    public void trashList(List<T> list, String updater) {
        list.forEach(t -> trashList(t, updater));
    }

    /**
     * 恢复删除
     */

    public void recoveryList(T t, String updater) {
        t.setUpdater(updater);
        t.setActivate(1);
        t.setUpdateTime(new Date());
        int i = getMapper().updateById(t);
        if (i == 0) throw new DAOException("恢复失败！没找到指定记录！");
    }

    public void recoveryList(List<T> list, String updater) {
        list.forEach(t -> recoveryList(t, updater));
    }

    /**
     * 物理删除
     */
    public void deleteById(Serializable id) {
        int i = getMapper().deleteById(id);
        if (i != 1)
            throw new DAOException("删除失败！没有找到对应的记录！");
    }

    public void delete(T t) {
        deleteById(t.getId());
    }

    public void deleteByIds(List<Serializable> ids) {
        int i = getMapper().deleteBatchIds(ids);
        if (ids.size() != i)
            throw new DAOException("批量删除失败！已删除记录数和需要删除的记录数不对等！");
    }

    public void deleteList(List<T> list) {
        List<Serializable> ids = list.stream().map(T::getId).collect(Collectors.toList());
        deleteByIds(ids);
    }

    /**
     * 合并 createOrUpdate对象
     * 如果record已经持久化，则返回一个更新对象
     * 如果record未持久化，则返回一个创建对象
     */
    private T mergeCreateObject(T record, String operator) {
        record.setCreator(operator);
        record.setUpdater(operator);
        if (record.getCreateTime() == null) record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        if (record.getActivate() == null) record.setActivate(1);
        return record;
    }

    private T mergeUpdateObject(T record, String operator) {
        record.setUpdateTime(new Date());
        record.setUpdater(operator);
        return record;
    }

    /**
     * 插入并在insert语句中剔除null字段
     */
    public T insert(T record, String operator) {
        int i = getMapper().insert(mergeCreateObject(record, operator));
        if (i == 0) throw new DAOException("插入失败！未知原因，返回数量为0");
        return record;
    }

    /**
     * 插入并在insert语句中填充所有字段
     */
    public T insertAllColumn(T record, String operator) {
        int i = getMapper().insert(mergeCreateObject(record, operator));
        if (i == 0) throw new DAOException("插入失败！未知原因，返回数量为0");
        return record;
    }


    /**
     * 保存列表
     *
     * @param records
     * @param creator
     * @return
     * @
     */
    public List<T> insertList(List<T> records, String creator) {
        for (T record : records) {
            insert(record, creator);
        }
        return records;
    }

    public List<T> insertAllColumnList(List<T> records, String creator) {
        for (T record : records) {
            insertAllColumn(record, creator);
        }
        return records;
    }

    /**
     * 更新，如果数据库中没有记录，则抛异常
     */
    public T update(T record, String updater) {
        int i = getMapper().updateById(mergeUpdateObject(record, updater));
        if (i == 0) throw new DAOException("更新失败！未知原因，返回数量为0");
        return record;
    }

    public List<T> updateList(List<T> records, String updater) {
        records.forEach(record -> update(record, updater));
        return records;
    }

    public T updateAllColumn(T record, String updater) {
        int i = getMapper().updateById(mergeUpdateObject(record, updater));
        if (i == 0) throw new DAOException("更新失败！未知原因，返回数量为0");
        return record;
    }

    public List<T> updateAllColumnList(List<T> records, String updater) {
        records.forEach(record -> update(record, updater));
        return records;
    }

    /**
     * 查找所有实体列表
     *
     * @return 返回实体列表
     */
    public List<T> selectAll() {
        return getMapper().selectList(new QueryWrapper<>());
    }

    public List<T> selectByIds(List<Serializable> ids) {
        return getMapper().selectBatchIds(ids);
    }

    /**
     * 查找所有记录数
     *
     * @return 返回实体记录数
     */
    public long countAll() {
        return getMapper().selectCount(new QueryWrapper<>());
    }

    /**
     * 查询是否存在记录
     */
    public boolean exists(Serializable id) {
        List<Map<String, Object>> maps = getMapper().selectMaps(new QueryWrapper<T>().eq("id", id));
        return CollectionUtils.isNotEmpty(maps);
    }

}
